package com.byls.controller;

import com.byls.dao.LawyerMapper;
import com.byls.pojo.Lawyer;
import com.byls.repository.LawyerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequestMapping("/lawyer")
@RestController
public class LawyerController {
    @Autowired
    private LawyerRepository lawyerRepository;
    @Autowired
    private LawyerMapper lawyerMapper;
    public <T> Page<T> listConvertToPage(List<T> list, Pageable pageable) {
        int start = (int)pageable.getOffset();
        int end = (start + pageable.getPageSize()) > list.size() ? list.size() : ( start + pageable.getPageSize());
        return new PageImpl<T>(list.subList(start, end), pageable, list.size());
    }

    @PostMapping("/findbyname")
    private Page<Lawyer> findByName(@RequestBody Map map){
        Pageable pageable= PageRequest.of(0,6);
        List<Lawyer>lawyerList=lawyerMapper.getLawyerByName(map.get("name").toString());
        return listConvertToPage(lawyerList,pageable);
    }
    @GetMapping("/findall")
    private List<Lawyer> getAll(){
        return lawyerMapper.getAllLawyer();
    }
    @GetMapping("/findall/{page}/{size}")
    private Page<Lawyer> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable= PageRequest.of(page-1,size);
        return lawyerRepository.findAll(pageable);
    }
    @PutMapping("/update")
    public String update(@RequestBody Lawyer lawyer){
       Lawyer res = lawyerRepository.save(lawyer);
        if(res!=null){
            return "success";
        }else {
            return "error";
        }
    }
    @PostMapping("/save")//tong guo RequestBody jiang jsonduixiang zhuanwei java duixiang
    public String save(@RequestBody Lawyer lawyer){
        Lawyer res = lawyerRepository.save(lawyer);
        if(res!=null){
            return "success";
        }else {
            return "error";
        }
    }
    @GetMapping("/findbyid/{id}")
    public Lawyer findById(@PathVariable("id") Integer id){
        return lawyerRepository.findById(id).get();
    }
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        lawyerRepository.deleteById(id);
    }
}
